/*
 * @Author: lx 664290587@qq.com
 * @Date: 2025-03-29 20:40:36
 * @LastEditors: lx 664290587@qq.com
 * @LastEditTime: 2025-03-29 20:40:44
 * @FilePath: \umi4-cachePage\src\utils\dynamicImportComponent.ts
 * @Description: 异步动态导入组件
 */

import { lazy } from 'react';

// 类型声明
interface WebpackContext<T> {
  keys: () => string[];
  (key: string): T;
}

// 获取组件上下文
const componentContext = (require as any).context(
  './components',
  true,
  /\/[A-Za-z0-9-]+?\/index\.tsx$/,
) as WebpackContext<{ default: React.ComponentType }>;

// 加载组件
export const dynamicLoadComponent = (componentName: string) => {
  const modulePath = componentContext
    .keys()
    .find((path) => path.includes(`/${componentName}/index.tsx`));

  if (!modulePath) {
    return lazy(() =>
      Promise.resolve({ default: () => <div>组件未找到</div> }),
    );
  }

  return lazy(async () => {
    try {
      const module = componentContext(modulePath);
      return { default: module.default };
    } catch (error) {
      console.error('组件加载失败:', error);
      return { default: () => <div>组件加载失败</div> };
    }
  });
};
